package io.renren.modules.oss.cloud;

import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.SnowFlake;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Service
public class LocalStorageService extends CloudStorageService {

    private final Logger logger = LoggerFactory.getLogger(LocalStorageService.class);

    @Value("${upload.local-base-file-name}")
    private String baseUploadFileName;

    @Override
    public String upload(byte[] data, String path) {
        try {
           logger.info("上传本地文件路径：{}", path);
           File file = new File(path);
           if (!file.exists()) {
               file.createNewFile();
           }
           FileOutputStream fos = new FileOutputStream(file);
           fos.write(data);
           fos.close();
        } catch (Exception e) {
            logger.error("上传文件失败，请核对本地上传文件配置信息: {}", e);
            throw new RRException("上传文件失败，请核对本地上传文件配置信息", e);
        }
        return path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(getBasePath(), suffix));
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RRException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(getBasePath(), suffix));
    }

    public String getPath(String prefix, String suffix) {
        //文件路径
        String path = DateUtils.format(new Date(), "yyyyMMdd");
        if(StringUtils.isNotBlank(prefix)){
            path = prefix + "/" + path;
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path + "/" + SnowFlake.createSnowFlake().nextIdString() + "-" + suffix;
    }

    private String getBasePath() {
        String projBasePath =  System.getProperty("user.dir");
        logger.info("projBasePath: {}", projBasePath);
        File file = new File(projBasePath);
        String uploadBasePath =  file.getParent() + "/" + baseUploadFileName;
        logger.info("uploadBasePath: {}", uploadBasePath);
        return uploadBasePath;
    }
}
